/*
 * HTML.C
 *
 * Convert VT100/ANSI escape sequences into HTML.
 *
 * Copyright (c) 2015 Malcolm J. Smith
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "cvtvt.h"

#define DEFAULT_COLOR (7)

DWORD   HtmlVersion = 5;
BOOLEAN TagOpen = FALSE;
BOOLEAN UnderlineOn = FALSE;

BOOL
HtmlInitializeStream(
    HANDLE hOutput,
    HANDLE hControl
    )
{
    ULONG  BytesTransferred;
    const CHAR szHeader[] = "<HTML><HEAD><TITLE>vttohtml output</TITLE></HEAD>";

    WriteFile(hOutput, szHeader, sizeof(szHeader) - 1, &BytesTransferred, NULL);
    if (HtmlVersion == 4) {
        const CHAR szVerHeader[] = "<BODY>"
                                   "<DIV STYLE=\"background-color: #000000; font-family: monospace;\">"
                                   "<B>"
                                   ;
        WriteFile(hOutput, szVerHeader, sizeof(szVerHeader) - 1, &BytesTransferred, NULL);
    } else {
        const CHAR szVerHeader[] = "<BODY><DIV STYLE=\"background-color: #000000; color: #c0c0c0; border-style: ridge; border-width: 4px; display: inline-block; font-weight: 900; font-family: monospace;\">";
        WriteFile(hOutput, szVerHeader, sizeof(szVerHeader) - 1, &BytesTransferred, NULL);
    }
    return TRUE;
}

BOOL
HtmlEndStream(
    HANDLE hOutput,
    HANDLE hControl
    )
{
    ULONG  BytesTransferred;
    if (TagOpen) {
        if (UnderlineOn) {
            WriteFile(hOutput, "</U>", 4, &BytesTransferred, NULL);
        }
        if (HtmlVersion == 4) {
            WriteFile(hOutput, "</FONT>", 7, &BytesTransferred, NULL);
        } else {
            WriteFile(hOutput, "</SPAN>", 7, &BytesTransferred, NULL);
        }
    }

    if (HtmlVersion == 4) {
        const CHAR szFooter[] = 
                                "</B>"
                                "</DIV>"
                                "</BODY></HTML>";
        WriteFile(hOutput, szFooter, sizeof(szFooter) - 1, &BytesTransferred, NULL);
    } else {
        const CHAR szFooter[] = "</DIV></BODY></HTML>";
        WriteFile(hOutput, szFooter, sizeof(szFooter) - 1, &BytesTransferred, NULL);
    }

    return TRUE;
}

BOOL
HtmlProcessAndOutputText(
    HANDLE hOutput,
    HANDLE hControl,
    LPSTR StringBuffer,
    ULONG BufferLength
    )
{
    CHAR   LookFor[] = {'<', '>', ' ', '\n', '\r', '\0'};
    LPSTR  CurrentPoint;
    ULONG  CurrentOffset = 0;
    ULONG  PreviouslyConsumed = 0;
    ULONG  BytesTransferred;

    //
    //  Scan through the string again looking for text that needs to be escaped in
    //  HTML, in particular greater than and less than since those denote tags
    //

    CurrentPoint = StringBuffer;

    do {
        CurrentOffset = memcspn(CurrentPoint, BufferLength - PreviouslyConsumed, LookFor);

        if (CurrentOffset > 0) {
            WriteFile(hOutput, CurrentPoint, CurrentOffset, &BytesTransferred, NULL);

            CurrentPoint = CurrentPoint + CurrentOffset;
            PreviouslyConsumed += CurrentOffset;
        }

        if (PreviouslyConsumed < BufferLength) {

            //
            //  Escape things that could be tags, and parse escape sequences
            //  we understand
            //
    
            if (*CurrentPoint == '<') {
                WriteFile(hOutput, "&lt;", 4, &BytesTransferred, NULL);
                CurrentPoint++;
                PreviouslyConsumed++;
            } else if (*CurrentPoint == '>') {
                WriteFile(hOutput, "&gt;", 4, &BytesTransferred, NULL);
                CurrentPoint++;
                PreviouslyConsumed++;
            } else if (*CurrentPoint == '\n') {
                WriteFile(hOutput, "<BR>", 4, &BytesTransferred, NULL);
                CurrentPoint++;
                PreviouslyConsumed++;
            } else if (*CurrentPoint == ' ') {
                WriteFile(hOutput, "&nbsp;", 6, &BytesTransferred, NULL);
                CurrentPoint++;
                PreviouslyConsumed++;
            } else if (*CurrentPoint == '\r') {
                CurrentPoint++;
                PreviouslyConsumed++;
            }
        }

    } while (PreviouslyConsumed < BufferLength);

    return TRUE;
}

BOOL
HtmlProcessAndOutputEscape(
    HANDLE hOutput,
    HANDLE hControl,
    LPSTR StringBuffer,
    ULONG BufferLength
    )
{
    LPSTR CurrentPoint = StringBuffer;
    ULONG CurrentOffset = 0;
    WORD  NewColor = DEFAULT_COLOR;
    ULONG BytesTransferred;
    ULONG RemainingLength;

    RemainingLength = BufferLength;

    //
    //  We expect an escape initiator (two chars) and a 'm' for color
    //  formatting.  This should already be validated, the check here
    //  is redundant.
    //

    if (BufferLength >= 3 &&
        CurrentPoint[BufferLength - 1] == 'm') {

        DWORD code;
        CHAR NewTag[128];
        BOOLEAN NewUnderline = FALSE;
        DWORD ColorTable[] = {0x000000, 0x800000, 0x008000, 0x808000, 0x000080, 0x800080, 0x008080, 0xc0c0c0,
                              0x808080, 0xff0000, 0x00ff00, 0xffff00, 0x0000ff, 0xff00ff, 0x00ffff, 0xffffff};

        CurrentPoint++;
        RemainingLength--;

        //
        //  For something manipulating colors, go through the semicolon
        //  delimited list and apply the changes to the current color
        //

        while (TRUE) {

            //
            //  Swallow either the ';' or '[' depending on whether we're
            //  at the start or an intermediate component
            //

            CurrentPoint++;
            RemainingLength--;

            code = memtoi(CurrentPoint, RemainingLength);
            if (code == 0) {
                NewColor = DEFAULT_COLOR;
                NewUnderline = FALSE;
            } else if (code == 1) {
                NewColor |= 8;
            } else if (code == 4) {
                NewUnderline = TRUE;
            } else if (code == 7) {
                NewColor = (WORD)(((NewColor & 0xf) << 4) | ((NewColor & 0xf0) >> 4));
            } else if (code == 39) {
                NewColor = (WORD)((NewColor & ~(0xf)) | (DEFAULT_COLOR & 0xf));
            } else if (code == 49) {
                NewColor = (WORD)((NewColor & ~(0xf0)) | (DEFAULT_COLOR & 0xf0));
            } else if (code >= 30 && code <= 37) {
                NewColor = (WORD)((NewColor & ~(0xf)) | (code - 30));
            } else if (code >= 40 && code <= 47) {
                NewColor = (WORD)((NewColor & ~(0xf0)) | ((code - 40)<<4));
            } else if (code >= 90 && code <= 97) {
                NewColor = (WORD)((NewColor & ~(0xf)) | 0x8 | (code - 90));
            } else if (code >= 100 && code <= 107) {
                NewColor = (WORD)((NewColor & ~(0xf0)) | 0x80 | ((code - 100)<<4));
            }

            //
            //  We expect this to end with an 'm' at the end of the string, or
            //  some other delimiter in the middle.  For paranoia maintain
            //  length checking.
            //

            CurrentOffset = memspn(CurrentPoint, RemainingLength, "0123456789");
            CurrentPoint += CurrentOffset;
            RemainingLength -= CurrentOffset;

            if (RemainingLength == 0 ||
                *CurrentPoint != ';') {
                
                break;
            }
        }

        if (TagOpen) {
            if (UnderlineOn) {
                WriteFile(hOutput, "</U>", 4, &BytesTransferred, NULL);
            }
            if (HtmlVersion == 4) {
                WriteFile(hOutput, "</FONT>", 7, &BytesTransferred, NULL);
            } else {
                WriteFile(hOutput, "</SPAN>", 7, &BytesTransferred, NULL);
            }
        }

        //
        //  Output the appropriate tag depending on the version the user wanted
        //

        if (HtmlVersion == 4) {
            sprintf(NewTag,
                    "<FONT COLOR=#%06x>",
                    ColorTable[NewColor & 0xf]);
        } else {
            sprintf(NewTag,
                    "<SPAN STYLE=\"color:#%06x;background-color:#%06x\">",
                    ColorTable[NewColor & 0xf],
                    ColorTable[(NewColor & 0xf0) >> 4]);
        }

        WriteFile(hOutput, NewTag, strlen(NewTag), &BytesTransferred, NULL);

        if (NewUnderline) {
            WriteFile(hOutput, "<U>", 3, &BytesTransferred, NULL);
        }
        UnderlineOn = NewUnderline;
        TagOpen = TRUE;
    }
    return TRUE;
}

BOOL
Html4SetFunctions(
    PCALLBACK_FUNCTIONS CallbackFunctions
    )
{
    HtmlVersion = 4;
    CallbackFunctions->InitializeStream = HtmlInitializeStream;
    CallbackFunctions->EndStream = HtmlEndStream;
    CallbackFunctions->ProcessAndOutputText = HtmlProcessAndOutputText;
    CallbackFunctions->ProcessAndOutputEscape = HtmlProcessAndOutputEscape;
    return TRUE;
}

BOOL
Html5SetFunctions(
    PCALLBACK_FUNCTIONS CallbackFunctions
    )
{
    HtmlVersion = 5;
    CallbackFunctions->InitializeStream = HtmlInitializeStream;
    CallbackFunctions->EndStream = HtmlEndStream;
    CallbackFunctions->ProcessAndOutputText = HtmlProcessAndOutputText;
    CallbackFunctions->ProcessAndOutputEscape = HtmlProcessAndOutputEscape;
    return TRUE;
}

// vim:sw=4:ts=4:et:
